package com.whu.MenuHub.controller;

import com.whu.MenuHub.exception.MenuHubException;
import com.whu.MenuHub.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin
@RequestMapping("/photo")
@Api(tags = "照片上传API")
public class UploadController {

    @PostMapping("/upload/{subfileName}")
    @ApiOperation("上传照片，subfilename对应avatar/food/order")
    public String uploadPhoto(MultipartFile file, @PathVariable(value = "subfileName") String subfileName) throws MenuHubException {
        try{
            String oldName=file.getOriginalFilename();
            String oleFileType=oldName.substring(oldName.lastIndexOf('.'));
            String newFileName=System.currentTimeMillis()+oleFileType;
            System.out.println(newFileName);
            FileUtil.uploadFile(file.getBytes(), FileUtil.getUploadFilePath(subfileName), newFileName);
            return "/photo/"+subfileName+"/"+newFileName;
        }
        catch (Exception e){
            throw new MenuHubException(MenuHubException.ErrorType.IO_EXCEPTION,"照片上传失败");
        }
    }
}
